package com.gateway.app.lb;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@SuppressWarnings("ALL")
public class HttpUtil {
    public static void apiConcurrent(String url, Map<String, String> params) {
        Integer count = 1;
        //创建线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 20, 0L, TimeUnit.SECONDS, new SynchronousQueue<>());
        //同步工具
        CountDownLatch latch = new CountDownLatch(count);
        Map<String, String> dataMap = new HashMap<>(1);
        dataMap.put("authorize","XXXXXXX");
        for (int i = 0; i < count; i++) {
            System.out.println("i:"+i);
            int finalI = i;
            pool.execute(() -> {
                try {
                    //访问网关的API接口  http://sit1.pay-gateway.sitcbi.com
                    //http://localhost:16000
                    //HttpUtil.doGet("http://sit1.pay-gateway.sitcbi.com/sso-base/getTest/getTest",dataMap);
                    String content = "{\n" +
                            "  \"input_image\":\"/home/ubuntu/stable-diffusion-webui/outputs/txt2img-images/2023-05-08/00000-697981760.png\",\n" +
                            "  \"driven_audio\":\"/home/ubuntu/stable-diffusion-webui/outputs/SadTalker/1234567.wav\",\n" +
                            "  \"taskid\":\"cp180805227652870269\"\n" +
                            "}";
                    String result = HttpUtil.doPost("http://127.0.0.1:8001/sso-base/dbq/genimagevideo", content, "JSON");
                    log.info("result i-{},:{}", finalI,result);
                } catch (IOException e) {
                    log.error(e.getMessage(),e);
                }finally {
                    latch.countDown();
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        pool.shutdown();
    }

    public static String doGet(String url, Map<String, String> params) throws IOException {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            //创建uri
            URIBuilder builder = new URIBuilder(url);
            if (!params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();
            //创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            List<NameValuePair> paramList = new ArrayList<>();
            RequestBuilder requestBuilder = RequestBuilder.get().setUri(new URI(url));
            requestBuilder.setEntity(new UrlEncodedFormEntity(paramList, Consts.UTF_8));
            httpGet.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            httpGet.setHeader(new BasicHeader("Accept", "*/*;charset=utf-8"));
            //执行请求
            response = httpClient.execute(httpGet);
            //判断返回状态是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }else {
                log.error("response.getStatusLine().getStatusCode():{}",response.getStatusLine().getStatusCode());
                log.error("resultString:{}",EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
        } catch (Exception e) {
            log.error("调用失败:{}",e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }
        log.info("打印：{}",resultString);
        return resultString;
    }

    /**
     * 发送 POST 请求（HTTP），不带输入数据
     *
     * @param apiUrl
     * @return
     * @throws ConnectTimeoutException
     */
    public static String doPost(String apiUrl) throws IOException {
        return doPost(apiUrl, new HashMap<String, String>());
    }

    /**
     * 发送 POST 请求（HTTP），K-V形式
     *
     * @param apiUrl API接口URL
     * @param params 参数map
     * @return
     * @throws ConnectTimeoutException
     */
    public static String doPost(String apiUrl, Map<String, String> params) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            List<NameValuePair> pairList = new ArrayList<>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
                pairList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    /**
     * 发送 POST 请求（HTTP），JSON形式
     *
     * @param apiUrl
     * @param content 内容
     * @return
     * @throws IOException
     */
    public static String doPost(String apiUrl, String content, String type) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            StringEntity stringEntity = new StringEntity(content, "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            if ("JSON".equals(type)) {
                stringEntity.setContentType("application/json");
            } else if ("XML".equals(type)) {
                stringEntity.setContentType("application/xml");
            } else {
                stringEntity.setContentType("text/plain");
            }
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    /**
     * 发送 POST 请求（HTTP），JSON形式 + url k-v参数
     * @param apiUrl
     * @param content
     * @param params
     * @param type
     * @return
     * @throws IOException
     */
    public static String doPost(String apiUrl, String content,Map<String, String> params, String type) throws IOException {
        // url参数拼接
        if (params != null) {
            int i = 0;
            StringBuffer param = new StringBuffer();
            for (String key : params.keySet()) {
                if (i == 0)
                    param.append("?");
                else
                    param.append("&");
                param.append(key).append("=").append(params.get(key));
                i++;
            }
            apiUrl += param;
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        log.info("本次请求apiUrl:"+apiUrl);
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            StringEntity stringEntity = new StringEntity(content, "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            if ("JSON".equals(type)) {
                stringEntity.setContentType("application/json");
            } else if ("XML".equals(type)) {
                stringEntity.setContentType("application/xml");
            } else {
                stringEntity.setContentType("text/plain");
            }
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            // System.out.println(response.getStatusLine().getStatusCode());
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }
    public static String doPost(String apiUrl, String content, String type,Map<String, String> headers) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        try {
            if (headers != null) {
                for (String headerName : headers.keySet()) {
                    httpPost.setHeader(headerName, headers.get(headerName));
                }
            }
            StringEntity stringEntity = new StringEntity(content, "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            if ("JSON".equals(type)) {
                stringEntity.setContentType("application/json");
            } else if ("XML".equals(type)) {
                stringEntity.setContentType("application/xml");
            } else {
                stringEntity.setContentType("text/plain");
            }
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            // System.out.println(response.getStatusLine().getStatusCode());
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }



    public static void main(String[] args){
        HttpUtil test = new HttpUtil();
        System.out.println("start");
        test.apiConcurrent(null,null);
        System.out.println("end");
        //获取当前时间天的时间
        long nowSecond = LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
        //1684080000
        System.out.println("nowSecond:"+nowSecond);
    }

}